<script setup lang="ts">
import { ref } from 'vue'
import {
  getPhoneNumberApi,
  getOpenidAndNicknameApi,
  loginByWechatApi,
  registerByWechatApi,
  sendCodeApi,
  loginByCodeApi,
} from '@/services/login'
import { useMemberStore, useDeviceStore } from '@/stores'
import { onMounted } from 'vue'
const phonenumber = ref('')
const password = ref('')
const code = ref('')
const openid = ref('')
const memberStore = useMemberStore()
const deviceStore = useDeviceStore()
const current = ref(0)
const items = ['验证码登录', '密码登录']
/**
 * 手机号授权
 */
const getphonenumber = async (e: any) => {
  //console.log(e.detail.code+'获取用户手机')
  console.log(e.detail)
  const { detail } = e
  if (detail.errMsg === 'getPhoneNumber:ok') {
    //console.log('用户同意授权')
    const code = detail.code // 动态令牌
    console.log(code)
    const res = await getPhoneNumberApi(code)
    phonenumber.value = res.data
    if (res.msg === '对象正常') {
      getOpenid()
    }
  } else {
    console.log('用户拒绝授权')
  }
}

/**
 * 获取openid和昵称
 */
const getOpenid = async () => {
  const { code } = await uni.login()
  //console.log(code)
  const res = await getOpenidAndNicknameApi(code)
  //console.log(data)
  if (res.msg === '对象正常') {
    openid.value = res.data.openID
    //先登录，根据登录返回的msg看是否需要注册
    const loginres = await loginByWechatApi(openid.value)
    if (loginres.msg === '对象正常') {
      //已注册，直接登录
      memberStore.setProfile(loginres.data)
      deviceStore.getDeviceList()
      uni.switchTab({
        url: '/pages/index/index',
      })
    }
    //后台接口已更新
    if (loginres.msg === '该微信未绑定用户') {
      //未注册，直接注册
      const registerres = await registerByWechatApi(phonenumber.value, openid.value)
      //后台接口已更新
      if (registerres.msg === '该手机号已注册') {
        uni.showToast({
          title: '该手机号已注册,请前往app绑定微信',
          icon: 'none',
          duration: 2000,
        })
      }
      if (registerres.msg === '对象正常') {
        //注册成功，直接登录
        memberStore.setProfile(registerres.data)
        deviceStore.getDeviceList()
        uni.switchTab({
          url: '/pages/index/index',
        })
      }
    }
  } else {
    uni.showToast({
      title: '获取微信信息失败',
      icon: 'none',
      duration: 2000,
    })
  }
}

//验证码登录表单为了表单验证使用的手机号变量和直接微信登录的手机号变量不一样
//发送验证码
const time = ref(0)
const codeformData = ref({
  phone: '',
  code: '',
})
const coderules = ref({
  phone: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3456789]\d{9}$/, errorMessage: '请输入正确的手机号' },
    ],
  },
  code: {
    rules: [
      { required: true, errorMessage: '请输入验证码' },
      { pattern: /^\d{4}$/, errorMessage: '请输入正确的验证码' },
    ],
  },
})
const codeform = ref()
let timeId: any
const send = () => {
  if (time.value > 0) {
    return
  }
  codeform.value
    .validateField('phone')
    .then(async () => {
      console.log('手机号符合规则')
      time.value = 60
      await sendCodeApi(codeformData.value.phone)
      timeId = setInterval(() => {
        time.value--
        if (time.value <= 0) {
          clearInterval(timeId)
        }
      }, 1000)
    })
    .catch(() => {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
        duration: 2000,
      })
    })
}
//密码表单校验
const passwordformData = ref({
  phone: '',
  password: '',
})
const passwordrules = ref({
  phone: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3456789]\d{9}$/, errorMessage: '请输入正确的手机号' },
    ],
  },
  password: {
    rules: [
      { required: true, errorMessage: '请输入密码' },
      { minLength: 1, maxLength: 8, errorMessage: '密码长度在 8 个字符以内' },
    ],
  },
})
const passwordform = ref()
//快速注册登录
const loginByCode = async () => {
  console.log(code.value)
  const res = await loginByCodeApi({ phone: codeformData.value.phone, code: codeformData.value.code })
  console.log(res.data)
  if (res.msg === '对象正常') {
    console.log('登录成功')
    memberStore.setProfile(res.data)
    deviceStore.getDeviceList()
    uni.switchTab({
      url: '/pages/index/index',
    })
  } else if (res.msg === '验证码错误') {
    uni.showToast({
      title: '验证码错误',
      icon: 'none',
      duration: 2000,
    })
  }
}
const onClickItem = (e: any) => {
  if (current.value != e.currentIndex) {
    current.value = e.currentIndex
  }
}
onMounted(() => {
  clearInterval(timeId)
})
</script>

<template>
  <view class="viewport">
    <img src="@/static/babycare.png" alt="" class="logo" />
    <!-- tab栏切换，验证码和密码登录方式切换 -->

    <view class="tabs">
      <uni-segmented-control
        :current="current"
        :values="items"
        @clickItem="onClickItem"
        styleType="text"
        activeColor="#28bb9c"
      />
      <view v-show="current === 0">
        <uni-forms ref="codeform" :modelValue="codeformData" :rules="coderules" validateTrigger="bind">
          <uni-forms-item label="手机号" name="phone">
            <uni-easyinput
              class="bottom"
              v-model="codeformData.phone"
              placeholder="请输入手机号"
              :inputBorder="false"
              primaryColor="#c0c4cc"
            ></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item label="验证码" name="code">
            <uni-easyinput
              class="bottom"
              focus
              v-model="codeformData.code"
              placeholder="请输入验证码"
              :inputBorder="false"
              primaryColor="#c0c4cc"
              ><template #right>
                <view class="btn-send" @click="send" :class="{ active: time > 0 }">{{
                  time > 0 ? `${time}s后能再次发送` : '发送验证码'
                }}</view>
              </template>
            </uni-easyinput>
          </uni-forms-item>
        </uni-forms>
        <button class="button phone" @click="loginByCode">快速注册&登录</button>
      </view>
      <view class="content">
        <view v-show="current === 1">
          <uni-forms ref="passwordform" :modelValue="passwordformData" :rules="passwordrules" validateTrigger="bind">
            <uni-forms-item label="手机号" name="phone">
              <uni-easyinput
                class="bottom"
                v-model="passwordformData.phone"
                focus
                placeholder="请输入手机号"
                :inputBorder="false"
                primaryColor="#c0c4cc"
              ></uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="密码" name="password">
              <uni-easyinput
                class="bottom"
                focus
                v-model="passwordformData.password"
                placeholder="请输入密码"
                :inputBorder="false"
                primaryColor="#c0c4cc"
                type="password"
              ></uni-easyinput>
            </uni-forms-item>
          </uni-forms>
          <button class="button phone">密码登录</button>
        </view>
      </view>
    </view>

    <!--#ifdef APP-PLUS-->
    <view class="hint"> 为体验更多内容和确保您的账户安全，请先创建用户 </view>
    <view class="apply"> 申请获取以下权限 </view>
    <view class="info"> 获得你的公开信息（手机号、昵称、头像） </view>
    <button class="button phone" open-type="getPhoneNumber" @getphonenumber="getphonenumber">手机号快捷登录</button>
    <!--#endif-->
    <view class="protocol"> 登陆/注册表示您同意《用户协议》和《隐私政策》 </view>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  .viewport {
    height: 100%;
    position: relative;
    font-family: PingFangSC-regular;
    font-size: 26.923rpx;
    overflow: hidden;
    .logo {
      margin: 0 50%;
      transform: translateX(-50%);
      padding-top: 182.692rpx;
      width: 153.846rpx;
      height: 153.846rpx;
    }
    .hint {
      margin: 121.154rpx auto 0;
      width: 565.385rpx;
      height: 86.538rpx;
      line-height: 38.462rpx;
      color: rgba(16, 16, 16, 1);
      font-size: 26.923rpx;
    }
    .apply {
      margin: 132.692rpx auto 0;
      width: 565.385rpx;
      height: 38.462rpx;
      line-height: 38.462rpx;
      color: rgba(16, 16, 16, 1);
    }
    .info {
      margin: 28.846rpx auto 57.692rpx;
      width: 565.385rpx;
      height: 38.462rpx;
      line-height: 38.462rpx;
      color: rgba(190, 190, 190, 1);
    }
    .button {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 442.308rpx;
      height: 80rpx;
      font-size: 28rpx;
      border-radius: 72rpx;
      color: #fff;
    }
    .phone {
      background-color: #28bb9c;
    }
    .protocol {
      position: absolute;
      left: 73.077rpx;
      bottom: 57.692rpx;
      width: 605.769rpx;
      height: 38.462rpx;
      line-height: 38.462rpx;
      color: rgba(187, 187, 187, 1);
      font-size: 26.923rpx;
      font-family: PingFangSC-regular;
    }
    .tabs {
      width: 625rpx;
      margin: 76.923rpx auto 0;
      .btn-send {
        color: #28bb9c;
        &.active {
          color: rgba(22, 194, 163, 0.5);
        }
      }
    }
  }
}
</style>
